﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using ST.Common.Util.Model;
using ST.Common.Util.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;

namespace ST.Buz.Web
{
	/// <summary>
	/// 验证请求的头部是否包含Session Key等认证信息
	/// </summary>
	[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
	public class ValidateSessionAttribute : Attribute, IActionFilter
	{
		/// <summary>
		/// 未授权时是否返回JSON格式响应代码
		/// </summary>
		public bool JsonFormat { get; set; }

		/// <summary>
		/// 未授权时返回HTTP响应代码
		/// </summary>
		public int StatusCode { get; set; }

		/// <summary>
		/// 未授权时重定向URL
		/// </summary>
		public string LoginUrl { get; set; }

		public ValidateSessionAttribute()
		{
			JsonFormat = false;
			StatusCode = (int)HttpStatusCode.Unauthorized;
		}

		public ValidateSessionAttribute(HttpStatusCode statusCode = HttpStatusCode.Unauthorized, bool jsonFormat = false, string loginUrl = null)
		{
			JsonFormat = jsonFormat;
			StatusCode = (int)statusCode;
			LoginUrl = loginUrl;
		}

		public void OnActionExecuted(ActionExecutedContext context)
		{
		}

		public void OnActionExecuting(ActionExecutingContext context)
		{
			try
			{
				UserSession sessionCurrent = HttpContextHelper.GetSessionFromRequest(context.HttpContext.Request, false);
			}
			catch
			{
				if (JsonFormat)
				{
					JsonResult result = new JsonResult(new
					{
						r = false,
						m = "未登录或登录已过期"
					});
					result.StatusCode = StatusCode;
					context.Result = result;
				}
				else
				{
					context.HttpContext.Response.StatusCode = StatusCode;//未授权
					if (string.IsNullOrEmpty(LoginUrl))
					{
						context.Result = new RedirectToActionResult("Login", "Sys_User", null);
					}
					else
					{
						context.Result = new RedirectResult(LoginUrl);
					}
				}
			}
		}
	}
}
